﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Common;
using System.Reflection;
//using YSocketClient;
using BYClient;
using User;
using User.YEventArgs;

namespace Yugi.Client
{
    public partial class SupervisorModel : BaseModel, Common.ISupervisor
    {
        public PlayerModel Nguoi_Choi;
        public PlayerModel Doi_Thu;

        public TombModel Mo_Nguoi_Choi;
        public TombModel Mo_Doi_Thu;

        public TableModel TableGame;
        public TurnModel Turn;

        public ViewDetailModel Viewdetail;

        public System.Windows.Controls.UserControl win;
        /// <summary>
        /// Cho Phep Phat tinh hieu Skip hay khong ( Chi co nguoi dang trong luot moi co quyen Skip)
        /// </summary>
        public bool AllowSkip { get; set; }

        
        //YClient socket;

        ClientManager client;

        #region Offline Test
        private bool OfflineTest = false;
        #endregion
        public SupervisorModel(int port,System.Windows.Controls.UserControl win)
        {
            this.win = win;
            //socket = new YClient();
            //socket.win = win;
            //socket.Connect(Program.IP_SERVER, port);
            //socket.OnReceiveData += new EventHandler<EventReceiveMessareArgs>(socket_OnReceiveData);

            client = new ClientManager();
            client.table_connection.Receive_From_Table += new EventHandler<ReceiveEventArgs>(table_connection_Receive_From_Table);
            client.table_connection.Connect(Program.IP_SERVER, Program.PORT_SERVER);
            TableGame = new TableModel();
            AllowSkip = true;
            
            // Init Request Manager
            Yugi.Client.DataModel.RequestAPI.super = this;

            OfflineTest = false;
            //Init_Download();
        }

        
        public SupervisorModel(System.Windows.Controls.UserControl win)
        {
            this.win = win;
            TableGame = new TableModel();
            AllowSkip = true;

            // Init Request Manager
            Yugi.Client.DataModel.RequestAPI.super = this;


            OfflineTest = true;
            //Init_Download();
        }

        void Init_Download()
        {
            //string path = System.IO.Directory.GetCurrentDirectory() + "\\player";
            //string ip = Program.IP_DOWNLOAD_CARD_SERVER;
            //List<string> param = new List<string>();
            //param.Add(ip);
            //param.Add(path);
            //System.Threading.ThreadPool.QueueUserWorkItem(new System.Threading.WaitCallback(Converter.ConvertData.Init_DownloadFile),param);
        }

        void socket_OnReceiveData(object sender, EventReceiveMessareArgs e)
        {
            Common.YMSG mss = (Common.YMSG)e.data[0];
            byte[] d= new byte[e.data.Length - 1];
            Buffer.BlockCopy(e.data, 1, d, 0, e.data.Length-1);
            this.ReciveMessageFromServer(mss, d);
        }

        void table_connection_Receive_From_Table(object sender, ReceiveEventArgs e)
        {
            Common.YMSG mss = (Common.YMSG)e.data[0];
            byte[] d = new byte[e.data.Length - 1];
            Buffer.BlockCopy(e.data, 1, d, 0, e.data.Length - 1);
            Action invoke = () => {
                this.ReciveMessageFromServer(mss, d);
            };
            this.win.Dispatcher.Invoke(invoke);
            
        }

        public void ReceiveMessageFromChildren(ClientMSG message, params object[] param)
        {
            switch (message)
            {
                case ClientMSG.PrintCard:
                    Viewdetail.ReceiveMessageFromSupervisor(message, param);
                    break;
                case ClientMSG.LenBaiXong:
                    // Card x y Trang Thai
                    SendMessageToServer(YMSG.CARD_LENBAI_XONG, param);
                    break;
                case ClientMSG.DoiCongThu:
                    //Card Trang Thai Moi
                    SendMessageToServer(YMSG.CARD_DOITRANGTHAI, param);
                    break;
                case ClientMSG.LenBaiSpellXong:
                    // card x y Trang Thai
                    SendMessageToServer(YMSG.CARD_LENBAI_SPELL_XONG, param);
                    break;
                case ClientMSG.LenBaiTrapXong:
                    // card x y Trang Thai
                    SendMessageToServer(YMSG.CARD_LENBAI_TRAP_XONG, param);
                    break;
                
            }
        }

        /// <summary>
        /// Tim tat ca cac cho co the
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public CardModel Find_Card_All(int id)
        {
            foreach (var item in Nguoi_Choi.YListCard)
            {
                if (item.YCard.ID == id)
                    return item;
            }
            foreach (var item in Nguoi_Choi.YBaiTrenBan)
            {
                if (item.YCard.ID == id)
                    return item;
            }
            foreach (var item in Doi_Thu.YBaiTrenBan)
            {
                if (item.YCard.ID == id)
                    return item;
            }
            CardModel result = Mo_Nguoi_Choi.FindAsCardModel(id);
            if (result != null)
                return result;
            
            result = Mo_Doi_Thu.FindAsCardModel(id);
            if (result != null)
                return result;

            foreach (var item in Nguoi_Choi.YDeck)
            {
                if (item.YCard.ID == id)
                    return item;
            }

            return null;
        }
        #region ISupervisor Members
        
        public void ReciveMessageFromServer(YMSG message, params object[] param)
        {
            try
            {
                Type t = typeof(SupervisorModel);
                MethodInfo handler = t.GetMethod("ProcessFromServer_" + message.ToString(), BindingFlags.NonPublic | BindingFlags.Instance);
                handler.Invoke(this, new object[] { param });
            }
            catch (Exception ex)
            {
                System.Windows.MessageBox.Show("Error" + message);
            }
            
            
        }

        public void ReciveMessageFromServer(YMSG message,  byte[] data)
        {
            try
            {
                MyConsole.WriteLine("Recive " + message + " " + data.Length + " byte");
                converter.ConvertReceive(message, data, this);

            }
            catch (System.Exception ex)
            {
                System.Windows.MessageBox.Show("Error Convert : " + message);
            }
            
            
        }

        public void SendMessageToServer(YMSG message, params object[] param)
        {
            try
            {
                converter.ConvertSend(message, param);
                MyConsole.WriteLine("Send "+message +" "+ param.Length + " byte");
                if (!OfflineTest)
                    //socket.SendMessage(converter.Result_Send.ToArray());
                    client.table_connection.SendMessage(converter.Result_Send.ToArray());
            }
            catch(Exception ex)
            {
                if(!(message == YMSG.PLAYER_LOGOUT))
                System.Windows.MessageBox.Show("Send Error : " + message);
            }
        }

        Yugi.Client.Converter.ConvertData converter = new Yugi.Client.Converter.ConvertData();
        #endregion

        public Action<SupervisorModel> InitCuaSo;
    }
}
